<template>
  <div style="padding: 15px">
    <el-form
      ref="formInline"
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
    >
      <el-form-item prop="taskDesc">
        <el-input
          v-model="formInline.taskDesc"
          placeholder="任务名称"
          class="el-input--mini"
          prefix-icon="el-icon-search"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item prop="taskStatus">
        <el-select
          v-model="formInline.taskStatus"
          clearable
          placeholder="运行状态"
          class="el-input--mini"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          class="el-button--mini"
          @click="onSubmit"
        >查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="el-button--mini"
          @click="onReset('formInline')"
        >重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-user"
          class="el-button--mini"
          @click="onAddTask('formInline')"
        >添加任务</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="fullscreenLoading"
      :data="tableData"
      border
      text-align="center"
      align="center"
      style="padding-top: 20px"
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
      stripe
      :row-style="{ height: '10px' }"
      :cell-style="{ padding: '0px' }"
    >
      <el-table-column prop="id" label="ID" width="70px" sortable />
      <el-table-column prop="taskDesc" label="任务名称" width="150px" />
      <el-table-column prop="taskKey" label="任务Handle" width="190px" />
      <el-table-column prop="taskCron" label="定时Cron" width="190px" />
      <el-table-column prop="initStartFlag" label="初始状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.initStartFlag | statusTagFilter">
            {{ scope.row.initStartFlag | taskStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="taskStatus" label="当前运行状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.taskStatus | statusTagFilter">
            {{ scope.row.taskStatus | taskStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        label="创建时间"
        width="180px"
        sortable
      >
        <template slot-scope="scope">
          <p>{{ scope.row.createdTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column
        prop="updatedTime"
        label="修改时间"
        width="180px"
        sortable
      >
        <template slot-scope="scope">
          <p>{{ scope.row.updatedTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作">
        <template slot-scope="scope">
          <div>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="editTask(scope.row, 'editTaskFormInline')"
            >编辑</el-button>
            <el-button
              :type="scope.row.taskStatus | statusBtnFilter"
              size="small"
              icon="el-icon-close"
              @click="startOrStopTask(scope.row, 'editTaskFormInline')"
            >{{ scope.row.taskStatus == 1 ? "暂停" : "启动" }}</el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="deleted(scope.row, 'editTaskFormInline')"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-divider />
    <div class="block">
      <el-pagination
        :total="page.totalCount"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      element-loading-text="拼命加载中"
    >
      <el-form
        ref="editTaskFormInline"
        :model="editTaskFormInline"
        :rules="rules"
      >
        <el-form-item
          label="任务描述"
          :label-width="formLabelWidth"
          prop="taskDesc"
        >
          <el-input
            v-model="editTaskFormInline.taskDesc"
            autocomplete="off"
            maxlength="30"
            prefix-icon="el-icon-edit"
            show-word-limit
            class="el-input--medium"
            size="small"
          />
        </el-form-item>
        <el-form-item
          label="JobHandler"
          :label-width="formLabelWidth"
          prop="taskKey"
        >
          <el-input
            v-model="editTaskFormInline.taskKey"
            autocomplete="off"
            maxlength="40"
            prefix-icon="el-icon-edit"
            show-word-limit
            class="el-input--medium"
          />
        </el-form-item>
        <el-form-item
          label="Cron"
          :label-width="formLabelWidth"
          prop="taskCron"
        >
          <el-input
            v-model="editTaskFormInline.taskCron"
            autocomplete="off"
            maxlength="20"
            prefix-icon="el-icon-edit"
            show-word-limit
            class="el-input--medium"
          />
        </el-form-item>
        <el-form-item
          label="Class"
          :label-width="formLabelWidth"
          prop="taskClass"
        >
          <el-input
            v-model="editTaskFormInline.taskClass"
            autocomplete="off"
            maxlength="90"
            prefix-icon="el-icon-edit"
            show-word-limit
            class="el-input--medium"
          />
        </el-form-item>
        <el-form-item
          label="是否程序初始运行"
          :label-width="formLabelWidth"
          prop="initStartFlag"
        >
          <el-select
            v-model="editTaskFormInline.initStartFlag"
            name="initStartFlag"
            placeholder="init"
            prefix-icon="el-icon-map-location"
            clearable
            class="el-input--medium"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="el-button--medium"
          @click="cancelChange('editTaskFormInline')"
        >取 消</el-button>
        <el-button
          class="el-button--medium"
          type="primary"
          @click="save('editTaskFormInline')"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  queryScheduledTaskPage,
  start,
  stop,
  save,
  deleted
} from '@/api/system/task.js'

export default {
  name: 'Dashboard',
  filters: {
    timefilters(val) {
      if (val == null || val === '') {
        return '暂无时间'
      } else {
        const d = new Date(val) // val 为表格内取到的后台时间
        const month =
          d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
        const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
        const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
        const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
        const times =
          d.getFullYear() +
          '-' +
          month +
          '-' +
          day +
          ' ' +
          hours +
          ':' +
          min +
          ':' +
          sec
        return times
      }
    },
    sexfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '男'
        } else {
          return '女'
        }
      }
    },
    taskStatusFilter(val) {
      const statusMap = {
        1: 'RUNNING',
        0: 'STOP'
      }
      return statusMap[val]
    },
    userStatusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '正常'
        }
        if (val === 2) {
          return '锁定'
        }
        if (val === 3) {
          return '删除'
        }
        if (val === 4) {
          return '非法'
        }
      }
    },
    statusTagFilter(val) {
      const statusMap = {
        1: 'success',
        0: 'info'
      }
      return statusMap[val]
    },
    statusBtnFilter(val) {
      const statusMap = {
        1: 'info',
        0: 'success'
      }
      return statusMap[val]
    }
  },
  data() {
    return {
      fullscreenLoading: true,
      options: [
        {
          value: 1,
          label: 'RUNNING'
        },
        {
          value: 0,
          label: 'STOP'
        }
      ],
      status: [
        {
          value: 1,
          label: 'RUNNING'
        },
        {
          value: 0,
          label: 'STOP'
        }
      ],
      formInline: {
        id: '',
        taskDesc: '',
        taskKey: '',
        initStartFlag: '',
        taskStatus: ''
      },
      dialogTitle: '',
      isAdd: true,
      editTaskFormInline: {
        id: '',
        taskKey: '',
        taskDesc: '',
        taskCron: '',
        taskClass: '',
        initStartFlag: ''
      },
      tableData: [],
      page: {
        rowCount: 10,
        currentPage: 1,
        pageSize: 10,
        pageCount: 2,
        totalCount: 0,
        orderBy: null,
        outofBounds: false,
        limitStart: 0
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '150px',
      editUserSex: '',
      transferData: [],
      rules: {
        taskDesc: [
          { required: true, message: '请填写任务描述', trigger: 'blur' }
        ],
        taskKey: [
          { required: true, message: '请填写JobHandler', trigger: 'blur' }
        ],
        taskCron: [
          { required: true, message: '请填写定时规则', trigger: 'blur,change' }
        ],
        taskClass: [
          { required: true, message: '请填写代码类', trigger: 'blur' }
        ],
        initStartFlag: [
          { required: true, message: '请选中初始运行状态', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['name'])
  },
  created() {
    this.queryTableData()
  },
  methods: {
    handleSizeChange(val) {
      this.page.pageSize = val
      this.queryTableData()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.queryTableData()
    },
    queryTableData() {
      this.fullscreenLoading = true
      var query = { page: this.page }
      var qq = Object.assign(query, this.formInline)
      queryScheduledTaskPage(qq).then((response) => {
        this.tableData = response.data.list
        this.page = response.data.page
      })
      setTimeout(() => {
        this.fullscreenLoading = false
      }, 1000)
    },
    onAddTask() {
      this.cleanForm()
      this.dialogTitle = '新增定时任务'
      this.dialogFormVisible = true
      this.isAdd = true
    },
    onSubmit() {
      this.queryTableData()
      this.$notify({
        title: '查询成功',
        duration: 1000,
        type: 'success'
      })
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
    },
    editTask(val, fromName) {
      this.dialogTitle = '编辑任务'
      this.editTaskFormInline.id = val.id
      this.editTaskFormInline.taskKey = val.taskKey
      this.editTaskFormInline.taskDesc = val.taskDesc
      this.editTaskFormInline.taskCron = val.taskCron
      this.editTaskFormInline.taskClass = val.taskClass
      this.editTaskFormInline.initStartFlag = val.initStartFlag
      this.dialogFormVisible = true
      this.isAdd = false
    },
    handleChange(value, direction, movedKeys) {
      // alert(value)
    },
    cancelChange(formName) {
      this.transferData = []
      this.dialogFormVisible = false
      this.$refs[formName].clearValidate()
    },
    save(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          this.editTaskFormInline.taskStatus = 0
          save(this.editTaskFormInline).then((response) => {
            this.$notify({
              title: response.msg,
              duration: 1000,
              type: 'success'
            })
            this.transferData = []
            this.dialogFormVisible = false
            this.queryTableData()
          })
        } else {
          return false
        }
      })
    },
    startOrStopTask(row, formName) {
      const title = row.taskStatus === 1 ? '暂停' : '启动'
      this.$confirm(
        '确认要' + title + '该任务: ' + row.taskDesc + ' 吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          console.log(row.taskStatus === 1)
          if (row.taskStatus === 1) {
            stop({ taskKey: row.taskKey }).then((response) => {
              this.queryTableData()
              this.$notify({
                title: response.msg,
                duration: 1000,
                type: 'success'
              })
            })
          } else {
            start({ taskKey: row.taskKey }).then((response) => {
              this.queryTableData()
              this.$notify({
                title: response.msg,
                duration: 1000,
                type: 'success'
              })
            })
          }
        })
        .catch(() => {})
    },
    deleted(row, formName) {
      this.$confirm('确认要删除该任务: ' + row.loginName + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleted({ taskKey: row.taskKey }).then((response) => {
            this.$notify({
              title: response.msg,
              duration: 1000,
              type: 'success'
            })
            this.cleanForm()
            this.queryTableData()
          })
        })
        .catch(() => {})
    },
    closeDialog(done) {
      done()
      if (this.isAdd) {
        location.reload()
      }
    },
    // 时间格式化
    dateFormat(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc != null) {
        const dateMat = new Date(
          parseInt(daterc.replace('/Date(', '').replace(')/', ''), 10)
        )
        const year = dateMat.getFullYear()
        const month = dateMat.getMonth() + 1
        const day = dateMat.getDate()
        const hh = dateMat.getHours()
        const mm = dateMat.getMinutes()
        const ss = dateMat.getSeconds()
        const timeFormat =
          year + '/' + month + '/' + day + ' ' + hh + ':' + mm + ':' + ss
        return timeFormat
      }
    },
    cleanForm() {
      this.editTaskFormInline.id = ''
      this.editTaskFormInline.taskKey = ''
      this.editTaskFormInline.taskDesc = ''
      this.editTaskFormInline.taskStatus = ''
      this.editTaskFormInline.initStartFlag = ''
      this.editTaskFormInline.taskCron = ''
      this.editTaskFormInline.taskClass = ''
    }
  }
}
</script>

<style scoped>
::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center !important;
}
</style>
